package com.youlu.campus.service.ranking;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.base.base.PageQueryRequest;
import com.youlu.campus.entity.UserActivityPointDetail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserActivityPointDetailService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserActivityPointRankingService userActivityPointRankingService;

    public Page<UserActivityPointDetail> list(String userId, PageQueryRequest pageQueryRequest) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        if (StringUtils.isNotBlank(pageQueryRequest.getActivityId())) {
            query.addCriteria(Criteria.where("activityId").is(pageQueryRequest.getActivityId()));
        }
        // 过滤领取纸质版证书
        query.addCriteria(Criteria.where("bizType").ne("ca-receive-paper"));
        PageRequest pageRequest = PageRequest.of(pageQueryRequest.getPageNo() - 1, pageQueryRequest.getPageSize());
        long count = this.mongoTemplate.count(query, UserActivityPointDetail.class);
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<UserActivityPointDetail> list = this.mongoTemplate.find(query.with(pageRequest), UserActivityPointDetail.class);
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }

    public void create(UserActivityPointDetail userActivityPointDetail) {
        log.info(":>>> 开始更新用户活动贡献值明细:{}", JSON.toJSONString(userActivityPointDetail));
        save(userActivityPointDetail);
        if ("add".equals(userActivityPointDetail.getAction())) {
            userActivityPointRankingService.updatePoint(userActivityPointDetail.getUserPO(), userActivityPointDetail.getActivityId(), userActivityPointDetail.getPoints());
        }
    }

    public UserActivityPointDetail save(UserActivityPointDetail userActivityPointDetail) {
        return this.mongoTemplate.save(userActivityPointDetail);
    }
}
